package net.lcheng.commons.utils;


import com.alibaba.fastjson.JSONObject;
import net.lcheng.utils.DESUtils;
import net.lcheng.utils.UploadResultModel;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;

/**
 * Created by qiliping on 16/4/7.
 */
public class UploadFileHelper {

    /**
     * @param file 图片
     */
    public static UploadFileResult uploadFileWithHttpMime(String url, MultipartFile file) {

        // 定义请求url
//        String uri = "http://120.76.114.76/mom-files/file_upload";

        // 实例化http客户端
//        HttpClient httpClient = new DefaultHttpClient();

        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 实例化post提交方式
        HttpPost post = new HttpPost(url);


        // 添加json参数
        try {
            // 实例化参数对象

//            MultipartEntity params = new MultipartEntity();

            MultipartEntityBuilder params =   MultipartEntityBuilder.create();
            // 图片文本参数
            params.addPart("textParams", new StringBody(
                    "{'user_name':'我的用户名','channel_name':'却道明','channel_address':'(123.4,30.6)'}",
                    Charset.forName("UTF-8")));

            // 设置上传文件
//            File file = new File(fileName);
            // 文件参数内容
            FileBody fileBody = new FileBody(convert(file));
            // 添加文件参数
            params.addPart("file", fileBody);
            params.addPart("fileName", new StringBody(file.getName()));
            // 将参数加入post请求体中
            post.setEntity(params.build());

            // 执行post请求并得到返回对象 [ 到这一步我们的请求就开始了 ]
            HttpResponse resp = httpClient.execute(post);

            // 解析返回请求结果
            HttpEntity entity = resp.getEntity();
            InputStream is = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuffer buffer = new StringBuffer();
            String temp;

            while ((temp = reader.readLine()) != null) {
                buffer.append(temp);
            }

            UploadFileResult result = JSONObject.parseObject(buffer.toString(),UploadFileResult.class);

            System.out.println("上传文件返回的结果:"+buffer);
            return result;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 转换文件格式
     * @param file
     * @return
     * @throws IOException
     */
    private static File convert(MultipartFile file) throws IOException {
        File convFile = new File(file.getOriginalFilename());
        convFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(convFile);
        fos.write(file.getBytes());
        fos.close();
        return convFile;
    }

    /**
     * @param file 图片
     */
    public static UploadResultModel uploadBase64Image(String url,String key,String userName, String base64) throws Exception {

        //访问服务器的sessionKey

//        String sessionKey = DESUtils.encrypt(pwd,key);
//        String dpwd = DESUtils.decrypt(sessionKey,key);

        DESUtils des2 = new DESUtils(key);// 自定义密钥
        String sessionKey = des2.encrypt(userName);

//        System.out.println("加密后的字符：" + sessionKey);
//        System.out.println("解密后的字符：" + des2.decrypt(sessionKey));

        CloseableHttpClient httpClient = HttpClients.createDefault();


        // 实例化post提交方式
        HttpPost post = new HttpPost(url);


        // 添加json参数
        try {
            // 实例化参数对象

//            MultipartEntity params = new MultipartEntity();

            MultipartEntityBuilder params =   MultipartEntityBuilder.create();
            // 图片文本参数
            params.addPart("textParams", new StringBody(
                    sessionKey,
                    Charset.forName("UTF-8")));



            // 设置上传文件
//            File file = new File(fileName);
            // 文件参数内容
//            FileBody fileBody = new FileBody(convert(file));
            // 添加文件参数
//            params.addPart("file", fileBody);
//            params.addPart("fileName", new StringBody(file.getName()));
            params.addTextBody("img",base64);
            // 将参数加入post请求体中
            post.setEntity(params.build());

            // 执行post请求并得到返回对象 [ 到这一步我们的请求就开始了 ]
            HttpResponse resp = httpClient.execute(post);

            // 解析返回请求结果
            HttpEntity entity = resp.getEntity();
            InputStream is = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuffer buffer = new StringBuffer();
            String temp;

            while ((temp = reader.readLine()) != null) {
                buffer.append(temp);
            }


            System.out.println("上传文件返回的结果:"+buffer);

            UploadResultModel result = JSONObject.parseObject(buffer.toString(),UploadResultModel.class);


            return result;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
        return null;
    }
}
